package com.cqyc.imview

import android.app.Activity
import android.media.AudioManager
import android.media.MediaPlayer
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMReceiveMessageOptInfo
import com.tencent.imsdk.v2.V2TIMValueCallback
import java.util.*
import kotlin.collections.ArrayList


class MessageMusicUtils(activity: Activity) {
    private val mActivity = activity

    fun messageMusic(userId: String?) {
        if (userId.isNullOrEmpty()) {
            return
        }
        val userList: MutableList<String> = ArrayList()
        userList.add(userId)
        V2TIMManager.getMessageManager().getC2CReceiveMessageOpt(
            userList,
            object : V2TIMValueCallback<List<V2TIMReceiveMessageOptInfo>> {
                override fun onSuccess(V2TIMReceiveMessageOptInfos: List<V2TIMReceiveMessageOptInfo>?) {
                    if (V2TIMReceiveMessageOptInfos == null || V2TIMReceiveMessageOptInfos.isEmpty()) {
                        //播放声音
                        initBeepSoundSus()
                        return
                    }
                    val info = V2TIMReceiveMessageOptInfos[0]
                    val option = info.c2CReceiveMessageOpt
                    if (option != V2TIMMessage.V2TIM_RECEIVE_NOT_NOTIFY_MESSAGE) {
                        //播放声音
                        initBeepSoundSus()
                    }
                }

                override fun onError(code: Int, desc: String?) {
                    //播放声音
                    initBeepSoundSus()
                }
            })
    }

    private fun initBeepSoundSus() {
        val mediaPlayer = MediaPlayer.create(mActivity, R.raw.witty)
        mActivity.volumeControlStream = AudioManager.STREAM_MUSIC
        mediaPlayer.start()
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                mediaPlayer.release()  // 3s后释放
                timer.cancel()
            }
        }, 3000)
    }
}